package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"month2/C/rpc_C/model/mysql"
	"month2/C/rpc_C/pkg"
	"strconv"

	"month2/C/rpc_C/internal/svc"
	"month2/C/rpc_C/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *order.CreateOrderRequest) (*order.CreateOrderResponse, error) {
	//1.用户未登录，不能下单
	var user mysql.User1
	err := mysql.DB.Where("id=?", in.UserId).Find(&user).Error
	if err != nil {
		logx.Error("用户未登录，不能下单")
		return nil, errors.New("用户未登录，不能下单")
	}
	if user.ID == 0 {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	//2.产品库存是否充足
	var goods mysql.Goods1
	mysql.DB.Find(&goods)
	if goods.GoodsNum < 1 {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	//生成订单
	OrderSn := uuid.NewString()
	//下单
	o := mysql.Order1{
		UserId:    int(in.UserId),
		GoodsId:   int(in.GoodsId),
		OrderSn:   OrderSn,
		PayType:   1,
		Amount:    goods.GoodsPrice,
		GoodsName: goods.GoodsName,
		GoodsImg:  goods.GoodsImg,
	}
	mysql.DB.Create(&o)
	//支付
	amount := strconv.FormatFloat(goods.GoodsPrice, 'f', 2, 64)
	alipay := pkg.NewAlipay()
	Url := alipay.Pay(goods.GoodsName, OrderSn, amount)
	return &order.CreateOrderResponse{
		OrderId: int64(o.ID),
		Url:     Url,
	}, nil
}
